<template>
  <div class="app-container">
    <div style="background: #FFFFFF;padding: 0.625rem;">
      <el-row :gutter="20">
        <el-col :span="5">
          <div class="filter-container">
            <el-button v-permission="'configgroup@add'" class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
              新增
            </el-button>
            <el-button circle style="float: right;" icon="el-icon-refresh" @click="getGroup" />
          </div>
          <el-table
            ref="singleTable"
            v-loading="listLoading1"
            :data="list_group"
            :header-cell-style="{background:'#eee',color:'#606266'}"
            fit
            highlight-current-row
            style="width: 100%;"
            @row-click="selectGroup"
          >
            <el-table-column label="分组名称" align="center">
              <template slot-scope="{row}">
                <span class="link-type">{{ row.title }}</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" align="center" width="95" class-name="small-padding fixed-width">
              <template slot-scope="{row,$index}">
                <el-button v-permission="'configgroup@edit'" title="编辑" type="primary" icon="el-icon-edit" circle @click.stop="handleUpdate(row)" />
                <el-button v-if="row.status!=='deleted'" v-permission="'configgroup@del'" title="删除" icon="el-icon-delete" circle type="danger" @click.stop="handleDelete(row,$index)" />
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="19">
          <div class="filter-container">
            <div v-if="isSearchBtn" style="display: inline-block">
              <el-input v-model="listQuery.title" placeholder="关键词" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="handleFilter" />
              <el-select v-model="listQuery.is_hid" placeholder="状态" clearable class="filter-item" style="width: 130px">
                <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
              </el-select>
              <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
              </el-button>
              <el-button class="filter-item" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </div>
            <el-button v-permission="'config@add'" class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreateConfig">
              新增
            </el-button>
            <el-button v-show="isShowBtn" v-permission="'config@del'" class="filter-item" type="danger" icon="el-icon-delete" @click="handleDeleteAll">
              批量删除
            </el-button>
            <el-button circle style="float: right;" icon="el-icon-search" @click="showBtn" />
            <el-button circle style="float: right;" icon="el-icon-refresh" @click="getList" />
          </div>
          <el-table
            v-loading="listLoading"
            :data="list"
            :header-cell-style="{background:'#eee',color:'#606266'}"
            fit
            highlight-current-row
            style="width: 100%;"
            @sort-change="sortChange"
            @select-all="showDeleteBtn"
            @select="showDeleteSelectBtn"
          >
            <el-table-column
              align="center"
              type="selection"
            />

            <el-table-column label="字典名称" align="left" width="110">
              <template slot-scope="{row}">
                <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
              </template>
            </el-table-column>
            <el-table-column label="字典编码" align="left" width="185">
              <template slot-scope="{row}">
                <span>{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="字典类型" align="center" width="80">
              <template slot-scope="{row}">
                <span>{{ row.type }}</span>
              </template>
            </el-table-column>
            <el-table-column label="字典值" align="center" width="180">
              <template slot-scope="{row}">
                <span class="overflow">{{ row.value }}</span>
              </template>
            </el-table-column>
            <el-table-column label="字典描述" align="center" width="170">
              <template slot-scope="{row}">
                <span class="overflow" :title="row.description">{{ row.description }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" width="140">
              <template slot-scope="{row}">
                <el-switch
                  :value="row.is_hid===0?'0':'1'"
                  active-text="启用"
                  inactive-text="禁用"
                  active-value="0"
                  inactive-value="1"
                  @change="isShow(row.is_hid,row.id,row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="排序" align="center" width="60">
              <template slot-scope="{row}">
                <span>{{ row.sort }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" width="150">
              <template slot-scope="{row}">
                <span>{{ row.created_at }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="180" class-name="small-padding fixed-width">
              <template slot-scope="{row,$index}">
                <el-button v-permission="'config@edit'" title="编辑" type="primary" icon="el-icon-edit" circle @click="handleUpdateConfig(row)" />
                <el-button v-if="row.status!=='deleted'" v-permission="'config@del'" title="删除" icon="el-icon-delete" circle type="danger" @click="handleConfigDelete(row,$index)" />
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="listQuery.p" :limit.sync="listQuery.limit" @pagination="getList" />
        </el-col>
      </el-row>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="70px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" maxlength="150" placeholder="请输入2-150字符的标题" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="temp.sort" maxlength="150" placeholder="默认0" />
        </el-form-item>
        <el-form-item label="状态" prop="is_hid">
          <el-select v-model="statusOptions[temp.is_hid]" class="filter-item" placeholder="请选择状态">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-switch-button" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button icon="el-icon-s-promotion" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisibleConfig">
      <el-form ref="dataFormConfig" :rules="configRules" :model="tempConfig" label-position="right" label-width="85px">
        <el-form-item label="字典名称" prop="title">
          <el-input v-model="tempConfig.title" maxlength="150" placeholder="请输入2-150字符的字典名称" />
        </el-form-item>
        <el-form-item label="字典标识" prop="name">
          <el-input v-model="tempConfig.name" maxlength="150" placeholder="请输入2-150字符的英文字母字典标识" />
        </el-form-item>
        <el-form-item label="字典类型" prop="type" placeholder="请选择">
          <el-select
            v-model="tempConfig.type"
            placeholder="请选择"
            @change="dictType"
          >
            <el-option
              v-for="item in dictTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-show="configOptionsShow" label="配置选项" prop="options">
          <el-input v-model="tempConfig.options" placeholder="请输配置选项，值:文字,例如：0:关闭,1开启" />
        </el-form-item>
        <el-form-item label="配置说明" prop="options">
          <el-input
            v-model="tempConfig.description"
            type="textarea"
            :rows="2"
            placeholder="请输入配置说明"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="tempConfig.sort" :min="0" :max="1000" label="排序" />
        </el-form-item>
        <el-form-item label="状态" prop="is_hid">
          <el-select v-model="statusOptions[tempConfig.is_hid]" class="filter-item" placeholder="请选择状态">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-switch-button" @click="dialogFormVisibleConfig = false">
          取消
        </el-button>
        <el-button icon="el-icon-s-promotion" type="primary" @click="dialogStatus==='create'?createConfigData():updateConfigData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getAll, createGroup, updateGroup, delGroup } from '@/api/config-group'
import { getLists, disable, enable, create, edit, del } from '@/api/config'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: '0', display_name: '正常' },
  { key: '1', display_name: '禁用' }
]

const dictTypeOptions = [
  { label: '文本', value: 'text' },
  { label: '单选', value: 'radio' },
  { label: '文本域', value: 'textarea' },
  { label: '图片', value: 'image' }
]
// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'PagePermission',
  components: { Pagination },
  directives: { waves, permission },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      list: null,
      list_group: null,
      total: 0,
      listLoading: true,
      listLoading1: true,
      listQuery: {
        p: 1,
        id: undefined,
        limit: 10,
        title: undefined,
        is_hid: undefined,
        sort: '+id'
      },
      calendarTypeOptions,
      sortOptions: [{ label: 'ID正序排序', key: '+id' }, { label: 'ID倒序排序', key: '-id' }],
      statusOptions: ['启用', '禁用'],
      dictTypeOptions,
      ps: '',
      temp: {
        id: undefined,
        title: '',
        sort: 0,
        is_hid: '0'
      },
      tempConfig: {
        id: undefined,
        title: '',
        name: '',
        group_id: undefined,
        type: '',
        options: '',
        description: '',
        sort: 0,
        is_hid: 0
      },
      dialogFormVisible: false,
      dialogFormVisibleConfig: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        title: [{ required: true, message: '标题必填', trigger: 'change' }]
      },
      configRules: {
        title: [{ required: true, message: '字典名称必填', trigger: 'change' }],
        name: [{ required: true, message: '字典标识必填', trigger: 'change' }],
        type: [{ required: true, message: '字典类型必填', trigger: 'change' }]
      },
      isShowSwitch: '',
      ids: [],
      isSearchBtn: false,
      isShowBtn: false,
      configOptionsShow: false
    }
  },
  created() {
    this.getGroup()
  },
  methods: {
    getList() {
      this.listLoading = true
      getLists(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    showBtn() {
      if (this.isSearchBtn === false) {
        this.isSearchBtn = true
      } else {
        this.isSearchBtn = false
      }
    },
    getGroup() {
      this.listLoading1 = true
      getAll().then(response => {
        this.list_group = response.data
        this.listLoading1 = false
        this.$refs.singleTable.setCurrentRow(response.data[0])
        this.listQuery.id = response.data[0].id
        this.getList()
      })
    },
    selectGroup(row, column, event) {
      this.listQuery.id = row.id
      this.getList()
    },
    dictType(value) {
      this.configOptionsShow = value === 'radio'
    },
    isShow(isShow, id, row) {
      const data = {}
      data.ids = id
      if (isShow === false) {
        disable(data).then(response => {
          row.is_hid = '1'
          this.$message({
            message: response.message,
            type: 'success'
          })
        })
      } else {
        enable(data).then(response => {
          row.is_hid = '0'
          this.$message({
            message: response.message,
            type: 'success'
          })
        })
      }
    },
    showDeleteBtn: function(selection) {
      this.ids = []
      Object.keys(selection).forEach((key) => {
        this.ids.push(selection[key].id)
      })
      this.isShowBtn = this.ids.length > 0
    },
    showDeleteSelectBtn: function(selection, row) {
      this.ids = []
      Object.keys(selection).forEach((key) => {
        this.ids.push(selection[key].id)
      })
      this.isShowBtn = this.ids.length > 0
    },
    handleDeleteAll() {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {}
        data.ids = this.ids
        this.listLoading = true
        del(data).then(response => {
          this.ids = []
          this.getList()
          this.isShowBtn = false
          this.listLoading = false
          this.$message({
            message: response.message,
            type: 'success'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleFilter() {
      this.listQuery.p = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetQuery() {
      this.listQuery = {
        p: 1,
        limit: 10,
        title: undefined,
        is_hid: undefined,
        sort: '+id'
      }
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        sort: 0,
        is_hid: '0'
      }
    },
    resetTempConfig() {
      this.tempConfig = {
        id: undefined,
        title: '',
        name: '',
        group_id: undefined,
        type: '',
        options: '',
        description: '',
        sort: 0,
        is_hid: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreateConfig() {
      this.resetTempConfig()
      this.dialogStatus = 'create'
      this.dialogFormVisibleConfig = true
      this.$nextTick(() => {
        this.$refs['dataFormConfig'].clearValidate()
      })
    },
    createConfigData() {
      this.$refs['dataFormConfig'].validate((valid) => {
        if (valid) {
          this.tempConfig.group_id = this.listQuery.id
          create(this.tempConfig).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisibleConfig = false
            this.$notify({
              title: 'Success',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createGroup(this.temp).then(response => {
            this.list_group.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdateConfig(row) {
      this.tempConfig = Object.assign({}, row) // copy obj
      if (this.tempConfig.type === 'radio') {
        this.configOptionsShow = true
      } else {
        this.configOptionsShow = false
      }
      this.dialogStatus = 'update'
      this.dialogFormVisibleConfig = true
      this.$nextTick(() => {
        this.$refs['dataFormConfig'].clearValidate()
      })
    },
    updateConfigData() {
      this.$refs['dataFormConfig'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.tempConfig)
          edit(tempData).then(() => {
            const index = this.list_group.findIndex(v => v.id === this.tempConfig.id)
            this.list.splice(index, 1, this.tempConfig)
            this.dialogFormVisibleConfig = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateGroup(tempData).then(() => {
            const index = this.list_group.findIndex(v => v.id === this.temp.id)
            this.list_group.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const tempData = {}
        tempData.ids = row.id
        delGroup(tempData).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list_group.splice(index, 1)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleConfigDelete(row, index) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const tempData = {}
        tempData.ids = row.id
        del(tempData).then(() => {
          this.dialogFormVisibleConfig = false
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style>
  .filter-item{
    margin-right: 0.3125rem;
  }
  .overflow{
      width:220px;
      overflow:hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow:ellipsis;
  }
</style>
